package se.rende.myrss;

import se.rende.myrss.data.ChannelUtil;
import se.rende.myrss.data.Constants;
import se.rende.myrss.data.MyRSSDataHelper;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ItemListFragment extends ListFragment implements
		LoaderManager.LoaderCallbacks<Cursor> {
	private static final int TUTORIAL_LIST_LOADER = 0x01;
	public static final String STATE_ACTIVATED_POSITION = "activated_position";
	public static final String STATE_SHOW_NEW = "show_new";
	public static final String ARG_CHANNEL_ID = "arc_channel_id";

	private Callbacks mCallbacks = sDummyCallbacks;
	private int mActivatedPosition = ListView.INVALID_POSITION;
	private final ItemListViewBinder viewBinder = new ItemListViewBinder();

	private SimpleCursorAdapter adapter;
	private boolean showNew = true;
	private String channelId;
	private MyRSSDataHelper dataHelper;
	private ChannelUtil.ChannelInfo channelInfo;

	public ItemListFragment() {
	}

	public interface Callbacks {
		public void onItemSelected(String id);
	}

	private static Callbacks sDummyCallbacks = new Callbacks() {
		@Override
		public void onItemSelected(String id) {
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dataHelper = new MyRSSDataHelper(getActivity());
		Intent intent = getActivity().getIntent();
		channelId = intent.getStringExtra(ItemListFragment.ARG_CHANNEL_ID);
		if (channelId != null) {
			channelInfo = ChannelUtil.getChannelInfo(dataHelper, channelId);
			Log.d("ItemListFragment", "channelId=" + channelId
					+ " channelInfo=" + channelInfo);
			getActivity().setTitle(channelInfo.name);
			String[] uiBindFrom = { "title" };
			int[] uiBindTo = { se.rende.myrss.R.id.title };
			getLoaderManager().initLoader(TUTORIAL_LIST_LOADER, null, this);
			adapter = new SimpleCursorAdapter(getActivity()
					.getApplicationContext(),
					se.rende.myrss.R.layout.item_list_item, null, uiBindFrom,
					uiBindTo, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
			adapter.setViewBinder(viewBinder);

			setListAdapter(adapter);
		}
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		Log.d("qwe", "onViewCreated");
		if (savedInstanceState != null) {
			if (savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
				setActivatedPosition(savedInstanceState
						.getInt(STATE_ACTIVATED_POSITION));
			}
		}
	}

	public void setShowNew(boolean showNew) {
		this.showNew = showNew;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException(
					"Activity must implement fragment's callbacks.");
		}

		mCallbacks = (Callbacks) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mCallbacks = sDummyCallbacks;
	}

	@Override
	public void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);
		mCallbacks.onItemSelected(Long.toString(id));
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (mActivatedPosition != ListView.INVALID_POSITION) {
			outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
		}
		outState.putBoolean(STATE_SHOW_NEW, showNew);
		Log.d("ILF.onSaveInstanceState", "showNew=" + showNew);
	}

	public void setActivateOnItemClick(boolean activateOnItemClick) {
		getListView().setChoiceMode(
				activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
						: ListView.CHOICE_MODE_NONE);
	}

	public void setActivatedPosition(int position) {
		if (position == ListView.INVALID_POSITION) {
			getListView().setItemChecked(mActivatedPosition, false);
		} else {
			getListView().setItemChecked(position, true);
		}

		mActivatedPosition = position;
	}

	public void refreshList() {
		getLoaderManager().restartLoader(TUTORIAL_LIST_LOADER, null, this);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		String[] projection = { "_id", "title", "seen", "star" };

		String cond = ChannelUtil.addCond("", (showNew ? "seen=0" : ""));
		cond = ChannelUtil.addCond(cond, channelInfo.getChannelIdCond());
		Log.d("ItemListFragment.onCreateLoader", "cond=" + cond);

		CursorLoader cursorLoader = new CursorLoader(getActivity(),
				Constants.CONTENT_URI_ITEM, projection, cond, null,
				"pub_date desc");
		return cursorLoader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		adapter.swapCursor(cursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		adapter.swapCursor(null);
	}

	public class ItemListViewBinder implements SimpleCursorAdapter.ViewBinder {
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
			if (columnIndex == 1) {
				TextView titleView = (TextView) view;
				String title = cursor.getString(1);
				titleView.setText(title);
				if (cursor.getInt(2) == 0) {
					titleView.setTypeface(null, Typeface.BOLD);
				} else {
					titleView.setTypeface(null, Typeface.NORMAL);
				}
				return true;
			}
			return true;
		}
	}
}
